package sys.knot.servlet;

import sys.knot.model.Indata;
import sys.knot.model.ResultConsumer;
import sys.knot.model.HttpServletRequestIndata;
import sys.knot.service.QueryService;
import sys.knot.validator.ValidationException;

import javax.inject.Inject;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(value = "/*")
public class ServiceServlet extends HttpServlet {

    @Inject
    QueryService queryService;

    protected void doJob(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //TODO return 404, if no endpoints match
        //TODO check user?

        //TODO serve static content from /etc/knot/html?

        Indata indata = new HttpServletRequestIndata(request);
        ResultConsumer consumer = new ResultConsumer(response);
        queryService.run(indata, consumer);

        consumer.close();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doJob(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doJob(request, response);
    }
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doJob(request, response);
    }
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doJob(request, response);
    }
}
